package com.kun.single_nacos;

import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * 发布/获取配置
 * */
public class PushAndGetConfig {

    public static void main(String[] args) throws NacosException, IOException {

        Properties properties = new Properties();
        // 设置nacos服务地址
        properties.setProperty("serverAddr", "192.168.2.183:8848");
        properties.setProperty("namespace", "a5d13b9e-58bc-4be6-ad0e-c85f1e63d552");

        // 构建ConfigService对象
        ConfigService configService = ConfigFactory.createConfigService(properties);

        // 发布配置
        boolean pushResult = configService.publishConfig("nacos-test", "DEFAULT_GROUP", "redis_port=6379");
        System.out.println("发布配置：" + pushResult);

        // 获取配置
        String config = configService.getConfig("nacos-test", "DEFAULT_GROUP", 2000);
        System.out.println("获取配置：" + config);

        // 订阅配置
        configService.addListener("nacos-test", "DEFAULT_GROUP", new Listener() {
            @Override
            public void receiveConfigInfo(String configInfo) {
                System.out.println(new Date() + ",监听到配置：" + configInfo);
            }

            @Override
            public Executor getExecutor() {
                return null;
            }
        });

        // 防止主线程退出，便于观察订阅的打印输出
        System.in.read();

    }
}
